<?php
namespace app\houtai\controller\system;
use app\houtai\controller\BaseController;
use think\db\Expression;

class MsgController extends BaseController
{

    private $MessageType = [1 => '通知', 2=> '补偿',3=>'称谓'];
    private $byShowScene = [1 => '大厅', 2 => '游戏'];
    private $bySysType = [1 => '喇叭消息', 2 => '系统消息', '提示消息'];
    private $UserType = [1 => '所有用户', 2 => '代理用户', 3 => '玩家用户', 4 => '指定用户'];
    private $GameType = ['MRoomCard' => '房卡', 'MGold' => '金币', 'MIntegral' => '积分'];

    /**
     * @brief  : 消息列表查询
     * @return : page
     * @details: http://ht.123pk123.com/system.msg/index.html
     */
    public function indexAction(){        
        $conds = [];
        $order = [];
        $CHANNELS = $this->GetAdminChannel();
        ////////////////////////////////////////////////////////////////////////////
        $channel = $this->request->param('channel/d', -1);
        if ($channel > 0 && array_key_exists($channel, $CHANNELS)) {
            $conds['Channel'][] = ['IN', array_keys($CHANNELS)];
            $conds['Channel'][] = ['EQ', $channel];
        } else if ($channel == 0) {
            $conds['Channel'] = ['EQ', 0];
        } else {
            $conds['Channel'] = ['IN', array_keys($CHANNELS)];
        }
        ////////////////////////////////////////////////////////////////////////////
        $mt = $this->request->param('mt/d', 0);
        $mt = array_key_exists($mt, $this->MessageType) ? $mt : 0;
        $ut = $this->request->param('ut/d', 0);
        $ut = array_key_exists($ut, $this->UserType) ? $ut : 0;
        $ispass = $this->request->param('IsPass/d', -1);
        if ($ispass >= 0 && in_array($ispass, [0, 1])) $conds['IsPass'] = $ispass;
        if ($mt > 0) {
            if ($mt=3){
                $conds['MsgType'] = ['eq',2];
                $conds['MGameLogo'] = ['gt',0];
            }else{
                $conds['MsgType'] = $mt;
            }
        }
        if ($ut > 0) $conds['UserType'] = $ut;
        /////////////////////////////////////////////////
        $orderMap = [
            'B' => 'ID',
            'C' => 'Channel',
            'D' => 'CreateDate',
            'E' => 'MsgType',
            'H' => 'UserType',
            'I' => 'IsPass',
            'J' => 'UpdateTime',
        ];
        $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'B';
        $order[$orderMap[$this->orderField]] = $this->orderDirection;
        $list = table('AccountsMessage', 'rydb.record')->where($conds)->order($order)->paginate();
        ////////////////////////////////////////////////////////////////////////////
        return $this->fetch('', [
            'CHANNELS' => $CHANNELS,
            'channel' => $channel,
            'MessageType' => $this->MessageType,
            'UserType' => $this->UserType,
            'mt' => $mt,
            'list' => $list,
            'ut' => $ut,
            'IsPass' => $ispass
        ]);
    }

    /**
     * @brief  : 消息详情
     * @return : page|JSON
     * @details:
     */
    public function detailAction()
    {
        $CHANNELS = $this->GetAdminChannel();
        $id = $this->request->param('id/d', 0);
        $Uid = $this->request->param('UserID/d', 0);
        if ($this->request->isGet()) { // 新建或读取
            if ($id > 0 && $Uid == 0) {
                $row = table('AccountsMessage', 'rydb.record')->where(['ID' => $id])->find();
                $strUsers1 = table('RecordAccountsMsg', 'rydb.record')->field('UserID')->where(['MsgID' => $id])->select();
                $strUsers = array_column($strUsers1, 'UserID');
                $strUsers = implode(",", $strUsers);
                $htmlType = 1;     //主系统消息详情界面
            } else if ($id > 0 && $Uid > 0) {
                $row = table('AccountsMessage', 'rydb.record')->where(['ID' => $id])->find();
                $row['UserType'] = 4;
                $htmlType = 2;      //用户消息系统详情界面
                $strUsers = $Uid;
            }
            $htmlType = 1;
            return $this->fetch('', [
                'Channels' => $row['Channel'] ?? [],
                'row' => $row ?? [],
                'strUsers' => $strUsers ?? '',
                'UserType' => $this->UserType,
                'MsgType' => $this->MessageType,
                'GameType' => $this->GameType,
                'CHANNEL' => $CHANNELS,
                'htmlType' => $htmlType,
            ]);
        } else if ($this->request->isPost()) {  // 添加/保存
            //
            $data = [
                'MsgTitle'   => $this->request->param('MsgTitle/s', '', 'trim'),
                'MsgContent' => $this->request->param('MsgContent/s', '', 'trim'),
                'MsgType'    => $this->request->param('MsgType/d', 0),
                'UserType'   => $this->request->param('UserType/d', 0),
                'MRoomCard'  => $this->request->param('MRoomCard/d', 0),
                'MGold'      => $this->request->param('MGold/d', 0),
                'MIntegral'  => $this->request->param('MIntegral/d', 0),
                'IsPass'     => $this->request->param('IsPass/d', 0),
                'CreateDate' => $this->request->param('CreateDate/d', 0, 'trim,YmdHis2Unix'),
                'IsRealTime' => $this->request->param('IsRealTime/d',0),
            ];
            //--- 验证器验证 ---
            $retn = $this->validate($data, [ // 按照顺序逐一判断
                'MsgTitle|消息标题'   => 'require|max:125',
                'MsgContent|消息内容' => 'require|max:1024',
                'MsgType|消息类型'    => 'require|integer|in:1,2,3',
                'UserType|用户类型'   => 'require|integer|in:1,2,3,4',
                'MRoomCard|房卡'      => "require|egt:0",
                'MGold|金币'          => "require|egt:0",
                'MIntegral|积分'      => "require|egt:0",
                'IsPass|禁用状态'     => 'integer|in:0,1',
                'CreateDate|开始时间' => "require|gt:0",
                'IsRealTime|实时状态' => 'integer|in:0,1',
            ]);
            if (true !== $retn) {
                return result([], 100, $retn);
            }
            $channel = $this->request->param('channel/d', 0);
            $data['CreateDate'] = YmdHis($data['CreateDate']);
            $data['Channel'] = $channel;
            if ($channel != 0 && array_key_exists($channel, $CHANNELS)) {   //判断渠道类型
                $conds_channel[] = ['IN', array_keys($CHANNELS)];
                $conds_channel[] = ['EQ', $channel];
            } else {
                $conds_channel = ['IN', array_keys($CHANNELS)];
            }
            //判断用户类型
            if ($data['UserType'] == 4) {           //指定用户
                $User4 = $this->request->param('Users/s', '', 'trim');
                if (strlen($User4) < 1) {
                    return result([], 101, '指定用户参数错误！');
                };
                $Users = explode(',', rtrim($User4, ',')); //
                $srvU['Users'] = $Users;
                $srvUser = json_encode($srvU);
                $AccountsType = 2;
                for ($i = 0; $i < count($Users); $i++) {
                    $User[$i]['UserID'] = $Users[$i];
                }
            } else if ($data['UserType'] == 3) {    //玩家用户
                $conds = ['UserID' => ['GT', 0]];
                $conds['AccountsType'] = 0;
                $conds['Channel'] = $conds_channel;
                $User = table('AccountsInfo', 'rydb.basic')->where($conds)->field('UserID')->select();

            } else if ($data['UserType'] == 2) {    //代理用户
                $conds = ['UserID' => ['GT', 0]];
                $conds['AccountsType'] = 1;
                $conds['Channel'] = $conds_channel;
                $User = table('AccountsInfo', 'rydb.basic')->where($conds)->field('UserID')->select();
            } else if ($data['UserType'] == 1) {    //所有用户
                $conds = ['UserID' => ['GT', 0]];
                $conds['Channel'] = $conds_channel;
                $srvUser = 101;
                $AccountsType = 1;
                $User = table('AccountsInfo', 'rydb.basic')->where($conds)->field('UserID')->select();
            }
            ////////////////////////////////////////////////////////
            $db = table('AccountsMessage', 'rydb.record');
            $Userdb = table('RecordAccountsMsg', 'rydb.record');
            $data['UpdateTime'] = new Expression('GETDATE()');    //修改时间
            $oldUserType = table('AccountsMessage', 'rydb.record')->where(['ID' => $id])->value('UserType');
            if($data['IsRealTime'] == 1){
                $param = ['name'=>'RealTimeUserMessage','AccountsType'=>$AccountsType,'AccoutsID'=>$srvUser];
                $addr = substr($channel,1,4) + 1001;
                try { // 通知游戏服务器
                    $ret = CallGoSrv($param,$addr);
                } catch (Exception $e) {
                    $error = $e->getMessage();
                    $errno = $e->getCode();
                    return result([], $errno, "通知游戏服务器失败[{$error}]");
                }
            }
            if ($id > 0 && $Uid == 0) { // 修改
                if ($data['UserType'] != $oldUserType) {//有人员变动时删除+新增
                    $eax =$db->where(['ID' => $id])->update($data);
                    table('RecordAccountsMsg', 'rydb.record')->where(['MsgID' => $id])->delete();
                    for ($i = 0; $i < count($User); $i++) {
                        $res[] = ['MsgID' => $id, 'UserID' => $User[$i]['UserID'], 'IsRead' => 0,'MsgType'=>$data['MsgType'],'Channel'=>$channel];
                    }
                    $res =$Userdb->insertAll($res, true);
                } else {
                    $eax =$db->where(['ID' => $id])->update($data);
                }
            } else if ($id > 0 && $Uid > 0) {
                $msgid = $db->insertGetId($data);
                $eax =$Userdb->where(['UserID' => $Uid, 'MsgID' => $id])->update(['MsgID' => $msgid,'MsgType'=>$data['MsgType']]);
            } else {// 创建
                $MsgID = $db->insertGetId($data);   //获取自增id
                for ($i = 0; $i < count($User); $i++) {
                    $datas[] = ['MsgID' => $MsgID, 'UserID' => $User[$i]['UserID'], 'IsRead' => 0,'MsgType'=>$data['MsgType'],'Channel'=>$channel];
                }
                $eax =$Userdb->insertAll($datas, true);
            }
            return result([], 0);
        }
    }

    /**
     * @brief  : 删除公告
     * @return : JSON
     * @details:
     */
    public function deleteAction()
    {
        if (!$this->request->isPost()) {
            return result([], 100, '非法请求');
        }
        $id = $this->request->param('id/d', 0);
        $sysid = $this->request->param('sysid/d', 0);  //删除系统公告通知游戏服务器
        if ($sysid > 0){
            $eax = table('SysMessage', 'rydb.record')->where(['ID' => $sysid])->delete();
            $res = table('RecordAccountsMsg', 'rydb.record')->where(['MsgID' => $sysid,'MsgType'=>1024])->delete();
            return result([], 0,$html ?? '');
        }
        if ($id <= 0) {
            return result([], 101, '业务参数无效');
        }
        $eax = table('AccountsMessage', 'rydb.record')->where(['ID' => $id])->delete();
        $cond['MsgID'] = $id;
        $cond['MsgType'] = ['neq',1024];
        $eax2 = table('RecordAccountsMsg', 'rydb.record')->where($cond)->delete();
        return result([], 0);
    }

    /**
     * @brief  : 用户全部消息
     * @return : JSON
     * @details:
     */
    public function usermsgAction()
    {
        $conds = [];
        $order = [];
        ////////////////////////////////////////////////////////////////////////////
        $mt = $this->request->param('mt/d', 0);
        $mt = array_key_exists($mt, $this->MessageType) ? $mt : 0;
        $ut = $this->request->param('ut/d', 0);
        $ut = array_key_exists($ut, $this->UserType) ? $ut : 0;
        $ispass = $this->request->param('IsPass/d', -1);
        $search = $this->request->param('search/s', '', 'trim');
        if (!empty($search)) {
            if (is_numeric($search)) {
                $search = $this->request->param('search/d', 0);
                $conds['a.UserID|a.MsgID|b.GameID'] = $search;
            } else {
                $conds['b.NickName'] = ['LIKE', "%{$search}%"];
            }
        }
        if ($ispass >= 0 && in_array($ispass, [0, 1])) {
            $conds['c.IsPass'] = $ispass;
        }
        if ($mt > 0) {
            if($mt = 3){
                $conds['c.MGameLogo'] = ['gt',0];
                $conds['c.MsgType'] = ['eq',2];
            }else {
                $conds['c.MsgType'] = $mt;
            }
        }
        if ($ut > 0) {
            $conds['c.UserType'] = $ut;
        }
        $conds['a.MsgType'] = ['neq', '1024'];//用户消息不获取系统消息
        /////////////////////////////////////////////////
        $orderMap = [
            'B' => 'ID',
            'C' => 'GameID',
            'D' => 'CreateDate',
            'E' => 'MsgID',
            'F' => 'MsgType',
            'I' => 'MRoomCard',
            'G' => 'MGold',
            'K' => 'MIntegral',
            'L' => 'IsRead',
            'M' => 'ReadDate',
            'N' => 'UserType',
            'O' => 'IsPass',
        ];
        $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'B';
        $order[$orderMap[$this->orderField]] = $this->orderDirection;
        $list = table('RecordAccountsMsg a', 'rydb.record')->field([
            'a.ID','a.MsgID','a.UserID','a.IsRead','a.ReadDate','a.MsgType','a.delDate', 'b.NickName','c.MsgTitle', 'b.GameID', 'b.AccountsType', 'b.AccountImgUrl',  'c.MsgContent', 'c.MRoomCard', 'c.MGold', 'c.MIntegral', 'c.Channel', 'c.UserType', 'CreateDate', 'c.IsPass','C.MGameLogo'
        ])
            ->join('CYBasicDB.dbo.AccountsInfo b', 'b.UserID=a.UserID', 'LEFT')
            ->join('CYRecordDB.dbo.AccountsMessage c', 'c.ID=a.MsgID', 'LEFT')
            ->where($conds)->order($order)->paginate(10);
        ////////////////////////////////////////////////////////////////////////////
        return $this->fetch('', [
            'MessageType' => $this->MessageType,
            'UserType' => $this->UserType,
            'mt' => $mt,
            'list' => $list,
            'ut' => $ut,
            'IsPass' => $ispass
        ]);
    }

    /**
     * @brief  : 系统公告消息
     * @return : bool
     * @details:
     */
    public function sysmsgAction()
    {
        $conds = [];
        $order = [];
        $CHANNELS = $this->GetAdminChannel();
        ////////////////////////////////////////////////////////////////////////////
        $channel = $this->request->param('channel/d', -1);
        if ($channel > 0 && array_key_exists($channel, $CHANNELS)) {
            $conds['Channel'][] = ['IN', array_keys($CHANNELS)];
            $conds['Channel'][] = ['EQ', $channel];
        } else if ($channel == 0) {
            $conds['Channel'] = ['EQ', 0];
        } else {
            $conds['Channel'] = ['IN', array_keys($CHANNELS)];
        }
        ////////////////////////////////////////////////////////////////////////////
        $st = $this->request->param('st/d', 0);    //bySysType=消息类型
        $st = array_key_exists($st, $this->bySysType) ? $st : 0;
        $ss = $this->request->param('ss/d', -1);   //byShowScene=发布场景
        $ss = array_key_exists($ss, $this->byShowScene) ? $ss : -1;
        $rc = $this->request->param('rc/d', 0);    //byRollCount=滚动次数
        $ispass = $this->request->param('IsPass/d', -1);

        if ($ispass >= 0 && in_array($ispass, [0, 1])) $conds['IsPass'] = $ispass;
        if ($st > 0) $conds['bySysType'] = $st;
        if ($rc > 0) $conds['byRollCount'] = $rc;
        if ($ss >= 0) $conds['byShowScene'] = $ss;
        /////////////////////////////////////////////////
        $orderMap = [
            'B' => 'ID',
            'C' => 'Channel',
            'D' => 'CreateDate',
            'E' => 'bySysType',
            'H' => 'byShowScene',
            'I' => 'byRollCount',
            'J' => 'byPriority',
            'K' => 'IsPass',
        ];
        $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'B';
        $order[$orderMap[$this->orderField]] = $this->orderDirection;
        $list = table('SysMessage', 'rydb.record')->where($conds)->order($order)->paginate();
        ////////////////////////////////////////////////////////////////////////////
        return $this->fetch('', [
            'CHANNELS'=> $CHANNELS,
            'channel' => $channel,
            'byShowScene' => $this->byShowScene,
            'bySysType' => $this->bySysType,
            'st' => $st,
            'ss' => $ss,
            'list' => $list,
            'rc' => $rc,
            'IsPass' => $ispass
        ]);

    }


    /**
     * @brief  : 系统公告消息详情
     * @return : page|JSON
     * @details:
     */
    public function sysdetailAction()
    {
        $CHANNELS = $this->GetAdminChannel();
        $id = $this->request->param('id/d', 0);
        $row = table('SysMessage', 'rydb.record')->where(['ID' => $id])->find();
        if ($this->request->isGet()) { // 新建或读取
            return $this->fetch('', [
                'Channels' => $row['Channel'] ?? [],
                'CHANNEL' => $CHANNELS,
                'byShowScene' => $this->byShowScene,
                'bySysType' => $this->bySysType,
                'row' => $row ?? [],
            ]);
        } else if ($this->request->isPost()) {  // 添加/保存
            $ch= $this->request->param('channel/d', 0);
            $data = [
                'szTitle'     => $this->request->param('szTitle/s', '','trim'),
                'szContent'   => $this->request->param('szContent/s', '', 'trim'),
                'byShowScene' => $this->request->param('byShowScene/d', 0),
                'bySysType'   => $this->request->param('bySysType/d', 0),
                'byRollCount' => $this->request->param('byRollCount/d', 0),
                'byPriority'  => $this->request->param('byPriority/d', 0),
                'IsPass'      => $this->request->param('IsPass/d', 0),
            ];
            //--- 验证器验证 ---
            $retn = $this->validate($data, [ // 按照顺序逐一判断
                'szTitle|公告标题'     => 'require|max:255',
                'szContent|公告内容'   => 'require|max:1024',
                'byShowScene|公告范围' => 'require|integer|in:1,2',
                'bySysType|公告类型'   => 'require|integer|in:1,2,3',
                'byRollCount|滚动次数' => 'require|gt:0',
                'byPriority|优先级别'  => 'require|gt:0',
                'IsPass|禁用状态'      => 'integer|in:0,1',
            ]);
            if (true !== $retn) {
                return result([], 100, $retn);
            }
                //通知游戏服务器系统公告信息参数
            $param = [
                'name' =>'SendSystemMessage',
                'byShowScene'=>$data['byShowScene'],
                'bySysType'=>$data['bySysType'],
                'szTitle'=>$data['szTitle'],
                'szContent'=>$data['szContent'],
                'byRollCount'=>$data['byRollCount'],
                'byPriority' =>$data['byPriority'],
            ];
            //通知服务器的端口:渠道号后４位＋1000
            $addr = substr($ch,1,4)+1000;
            ////////////////////////////////////////////////////////
            $data['Channel'] = $this->request->param('channel/d', 0);
            $data['UpdateCount'] = $row['UpdateCount'] + 1;
            $data['UpdateAdminID'] = (int)session(config('auth.session')); //修改人员id
            $data['UpdateDate'] = new Expression('GETDATE()');    //修改时间

            $db = table('SysMessage', 'rydb.record');
            if ($id > 0) { // 修改
                if ($data['IsPass'] == 0 && $data['bySysType'] == 1){ //0=发布,通知游戏服务器,否则只做数据库存储
                    try { // 通知游戏服务器
                        $ret = CallGoSrv($param,$addr);//执行句柄，获取返回内容
                    } catch (Exception $e) {
                        $error = $e->getMessage();
                        $errno = $e->getCode();
                        return result([], $errno, "通知游戏服务器失败[{$error}]");
                    }
                }
                $eax = $db->where('ID', $id)->update($data);
            }else{// 创建
                if ($data['IsPass'] == 0 && $data['bySysType'] == 1) {
                    try { // 通知游戏服务器
                        $ret = CallGoSrv($param,$addr);
                    } catch (Exception $e) {
                        $error = $e->getMessage();
                        $errno = $e->getCode();
                        return result([], $errno, "通知游戏服务器失败[{$error}]");
                    }
                }
                $data['CreateDate'] = new Expression('GETDATE()');
                $data['CreateAdminID'] = (int)session(config('auth.session'));  //创建人员id
                $eax = $db->insert($data);
            }
            return result([], 0 ?? 101,$ret ?? '');
        }
    }
}

